package com.maozzi.service.acl.domain.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.acl.domain.RolePermissionDomainService;
import com.maozzi.service.acl.repository.mapper.RolePermissionMapper;
import com.maozzi.service.acl.repository.model.RolePermission;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限 - 角色对应权限 domain service
 *
 * @author maozi
 */
@Service
public class RolePermissionDomainServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionDomainService {

    @Override
    public List<RolePermission> getRolePermission(Long roleId) {
        LambdaQueryWrapper<RolePermission> query = Wrappers.lambdaQuery(RolePermission.class)
                .eq(RolePermission::getRoleId, roleId);

        return this.list(query);
    }

    @Override
    public List<RolePermission> getRolePermissions(List<Long> roleIds) {
        LambdaQueryWrapper<RolePermission> query = Wrappers.lambdaQuery(RolePermission.class)
                .in(RolePermission::getRoleId, roleIds);

        return this.list(query);
    }

    @Override
    public void clear(Long roleId) {
        LambdaUpdateWrapper<RolePermission> query = Wrappers.lambdaUpdate(RolePermission.class)
                .eq(RolePermission::getRoleId, roleId);
        this.remove(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Long roleId, List<Long> permissionIds) {
        ParamCheckUtil.notNull(roleId, "角色ID为空");
        ParamCheckUtil.notNull(permissionIds, "权限码为空");

        permissionIds = permissionIds.stream().distinct().collect(Collectors.toList());
        List<RolePermission> list = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            list.add(new RolePermission().setRoleId(roleId).setPermissionId(permissionId));
        }

        this.saveBatch(list);
    }
}
